<?php
namespace app\common\model;

use think\Model;

class Activity extends Model
{
    protected $table = "zj_activity";
    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';
    protected $Activity ;

	// 验证规则
	protected $rule = [
		//['id|优惠券id', ['require']],
	]; 
	
	// 验证场景
	protected $scene = [
        //'update' => ['id'],
    ];

    // 验证器
	public function intValidate(){
        $validate = new \think\Validate($this->rule);
        foreach ($this->scene as $k1=>$v1)
            $validate->scene($k1, $v1);
        return $validate;
    }

    /**
     * 添加活动
     */
    public function insertActivity($data = array()){
	    $act = new Activity();
        $act->startTrans();
	    $glist = $data['goods_list'];
	    unset($data['goods_list']);
        $act->data($data)->save();
        if($glist != '0'){
            $result = $act->bindGoodsActivity($glist,$act->id);
            if($result){
                $act->commit();
                return true;
            }else{
                $act->rollback();
                return false;
            }
        }
        $act->commit();
        return $act->id;
    }

    public function bindGoodsActivity($glist=array(),$act_id = 0){
        if($act_id > 0){
            $act_goods = Db("goods")->where("goods_activity_id = $act_id")->value("group_concat(goods_id)");
            if(!empty($act_goods)){
                Db("goods")->where("goods_id in ($act_goods)")->update(["goods_activity_id"=>0]);
            }
        }
        $goods_id = implode($glist,",");
        $res = Db("goods")->where("goods_id in ($goods_id)")->update(["goods_activity_id"=>$act_id]);
        if($res !== false){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 更新活动
     */
    public function updateActivity($data = array()){
        $act = new Activity();
        $act->startTrans();
        $glist = $data['goods_list'];
        unset($data['goods_list']);
        $res = $act->save($data,['id'=>$data['id']]);
        if($glist != '0'){
            $result = $act->bindGoodsActivity($glist,$data['id']);
            if($result){
                $act->commit();
                return true;
            }else{
                $act->rollback();
                return false;
            }
        }
        $act->commit();
        return $res;
    }

    /**
     * 获取活动列表
    */
    public function getActivityList($pagesize){
        $now = time();
        $keyword = input('param.keyword');
        $where = [];
        if($keyword)
        {
            $where['act_name'] = ['like', "%$keyword%"];
        }
        //and join_btn = 1
        $act = new Activity();
        $data = $act->where($where)->where("use_type = 0 and status = 1 and end_time > $now and join_type != 0")->paginate($pagesize, false, [
            'query' => request()->param(),
        ]);
        return $data;
    }

    /**
     * 获取活动列表
     */
    public function getJoinActivityInfo($id){
        $now = time();
        $act = new Activity();
        $data = $act->where("id = $id and use_type = 0 and status = 1 and end_time > $now and join_type != 0")->find();
        return $data;
    }

    /**
     * 获取店铺活动列表
     */
    public function getStoreActivityList($store_id,$pagesize){
        $keyword = input('param.keyword');
        $where = [];
        if($keyword)
        {
            $where['act_name'] = ['like', "%$keyword%"];
        }
        $where['status'] = ['lt',2];
        $act = new Activity();
        $data = $act->where($where)->where('create_id','eq',$store_id)->paginate($pagesize, false, [
            'query' => request()->param(),
        ]);
        if(!empty($data)){
            foreach($data as $k => $v){
                if($v['end_time'] < time() && $v['status'] == 1){
                    $act->where('id','eq',$v['id'])->update(['status'=>0]);
                }
            }
        }
        return $data;
    }

    /**
     * 获取活动信息
     */
    public function getActivityInfo($id){
        $data = Db("zj_activity")->where("id = $id")->find();
        return $data;
    }

    /**
     * 获取店铺信息
    */
    public function getStoreinfo($merchant_id){
        $storelist = Db("store")
            ->field("store_merchant_id as store_id,store_name")
            ->where("store_verify_status = 2 and store_is_forever_close = 0 and store_is_close = 0 and store_is_delete = 0 ")
            ->where("store_merchant_id = $merchant_id")
            ->find();
        return $storelist;
    }

    /**
     * 处理报名
     */
    public function handleJoinActivity($data=[]){
        $goods_id = "";
        switch ($data['type']){
            case 1:
                $goods_id = implode($data['goods_list'],",");
                break;
            case 2:
                $goods_id = Db("goods")->alias("g")
                    ->join("store s","g.goods_store_id = s.store_id","left")
                    ->where("s.store_merchant_id = {$data['store_id']}")->value("group_concat(g.goods_id)");
                break;
            default:
                return false;
                break;
        }
        if(empty($goods_id)){
            return false;
        }
        $join_btn = Db("zj_activity")->where("id = {$data['id']}")->value("join_btn");
        if(intval($join_btn) != 1){
            return false;
        }
        $del = Db("goods")->where("goods_merchant_id = {$data['store_id']} and goods_activity_id = {$data['id']}")->update(["goods_activity_id"=>0,"goods_activity_selfrate"=>0]);
        $res = Db("goods")->where("goods_id in ($goods_id)")->update(["goods_activity_id"=>$data['id'],"goods_activity_selfrate"=>$data['store_rate']]);
        if($res !== false){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 获取报名平台活动商品信息列表
     */
    public function getJoinGoodsList($merchant_id,$id){
        $goods_list = Db("goods")->alias("g")
            ->join("store s","g.goods_store_id = s.store_id","left")
            ->join("goods_main_img gm","g.goods_id=gm.goods_id","left")
            ->field("g.goods_name,gm.goods_main_pic,g.goods_activity_selfrate")
            ->where("s.store_merchant_id = $merchant_id and g.goods_activity_id = $id and gm.goods_is_main_pic = 1 and g.goods_is_delete = 0")->select();
        if(empty($goods_list)){
            return false;
        }
        foreach($goods_list as $k => $v){
            $goods_list[$k]['goods_main_pic'] = config("oss_imgRootPath")."goods/main/".$v['goods_main_pic']."@!seller_store_face";
        }
        return $goods_list;
    }

    /**
     * 获取商家活动相关商品信息
     */
    public function getGoodsList($merchant_id,$page = 1){
        $goodslist = Db("goods")->alias("gs")
            ->join("goods_main_img gm","gs.goods_id=gm.goods_id","left")
            ->join("store st","st.store_id=gs.goods_store_id","left")
            ->field("gs.goods_name,gs.goods_id,gm.goods_main_pic,gs.goods_activity_id")
            ->where("st.store_merchant_id = $merchant_id and gm.goods_is_main_pic = 1 and gs.goods_is_delete = 0 and gs.goods_shelf_state = 2")
            ->limit(($page-1)*20,$page*20)
            ->select();
        foreach($goodslist as $k => $v){
            $goodslist[$k]['goods_main_pic'] = config("oss_imgRootPath")."goods/main/".$v['goods_main_pic']."@!seller_store_face";
        }
        return $goodslist;
    }

    /**
     * 删除活动
     */
    public function delActivity($id,$merchant_id){
        $act = new Activity();
        $res = $act->where(['id'=>$id])->update(['status'=>2,'delete_time'=>time()]);
        $res = Db("goods")->where(['goods_activity_id'=>$id])->update(['goods_activity_id'=>0,'goods_activity_selfrate'=>0]);
        return $res;
    }

    /**
     * 获取活动选择商品信息
     */
    public function getSelectGoods($ids){
        $goodslist = Db("goods")->alias("gs")
            ->join("goods_main_img gm","gs.goods_id=gm.goods_id","left")
            ->join("store st","st.store_id=gs.goods_store_id","left")
            ->field("gs.goods_name,gs.goods_id,gm.goods_main_pic,gs.goods_activity_id")
            ->where("gs.goods_id in ($ids) and gm.goods_is_main_pic = 1 and gs.goods_is_delete = 0")
            ->select();
        foreach($goodslist as $k => $v){
            $goodslist[$k]['goods_main_pic'] = config("oss_imgRootPath")."goods/main/".$v['goods_main_pic']."@!seller_store_face";
        }
        return $goodslist;
    }


    /**
     * 获取活动中商品列表
     */
    public function getDetailGoodsList($merchant_id){
        $goodslist = Db("goods")->alias("gs")
            ->join("goods_main_img gm","gs.goods_id=gm.goods_id","left")
            ->join("store st","st.store_id=gs.goods_store_id","left")
            ->field("gs.goods_name,gs.goods_id,gm.goods_main_pic,gs.goods_activity_id")
            ->where("st.store_merchant_id = $merchant_id and gm.goods_is_main_pic = 1 and gs.goods_is_delete = 0")
            ->select();
        foreach($goodslist as $k => $v){
            $goodslist[$k]['goods_main_pic'] = config("oss_imgRootPath")."goods/main/".$v['goods_main_pic']."@!seller_store_face";
        }
        return $goodslist;
    }

    /**
     * 获取活动中商品总页数
     */
    public function getGoodsPage($merchant_id){
        $goodsCount = Db("goods")->alias("gs")
            ->join("goods_main_img gm","gs.goods_id=gm.goods_id","left")
            ->join("store st","st.store_id=gs.goods_store_id","left")
            ->where("st.store_merchant_id = $merchant_id and gm.goods_is_main_pic = 1 and gs.goods_is_delete = 0")
            ->count();
        $page_count = ($goodsCount % 20 == 0) ? intval($goodsCount/20) : intval($goodsCount/20)+1;
        return $page_count;
    }

}

  





 
